package com.gitee.sliu.binlog5j.core.position;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gitee.sliu.binlog5j.core.config.RedisConfig;
import com.gitee.sliu.binlog5j.core.exception.Binlog5jException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.exceptions.JedisConnectionException;

/**
 * @author SLIU
 */
@Slf4j
public class RedisBinlogPositionHandler implements BinlogPositionHandler {

    private final JedisPool jedisPool;
    private final ObjectMapper objectMapper = new ObjectMapper();

    public RedisBinlogPositionHandler(RedisConfig redisConfig) {
        this.jedisPool = new JedisPool(new GenericObjectPoolConfig<>(), redisConfig.getHost(), redisConfig.getPort(), 1000, redisConfig.getPassword(), redisConfig.getDatabase());
    }

    @Override
    public BinlogPosition loadPosition(Long serverId) {
        try (Jedis jedis = jedisPool.getResource()) {
            String value = jedis.get(serverId.toString());
            if (value != null) {
                try{
                    return objectMapper.readValue(value,BinlogPosition.class);
                } catch (Exception e){
                    log.error("转换实体类型失败，原因是：{}",e.getMessage());
                }
            }
        } catch (JedisConnectionException e) {
            throw new Binlog5jException("Unable to connect to Redis host.");
        }
        return null;
    }

    @Override
    public void savePosition(BinlogPosition position) {
        try (Jedis jedis = jedisPool.getResource()) {
            jedis.set(position.getServerId().toString(), objectMapper.writeValueAsString(position));
        } catch (Exception e){
            log.error("获取位置失败了，原因是：{}",e.getMessage());
        }
    }
}
